<?php

namespace App\Models;

use App\Models\CommonModel as Model;

/**
 * Class UserModel
 * @package App\Models
 * @version May 9, 2018, 8:43 am UTC
 *
 * @property string nickname
 * @property string open_id
 * @property string sns_open_id
 * @property string union_id
 * @property string mobile
 * @property string|\Carbon\Carbon created_at
 * @property timestamp updated_at
 * @property string avatar
 * @property tinyint sex
 */
class UserModel extends Model
{
    public $table = 'user';
    
    public $fillable = [
        'nickname',
        'open_id',
        'sns_open_id',
        'union_id',
        'mobile',
        'status',
        'name',
        'birth',
        'created_at',
        'updated_at',
        'avatar',
        'is_active',
        'sex'
    ];

    public $searchable = [
        'id',
        'nickname',
        'open_id',
        'sns_open_id',
        'union_id',
        'mobile',
       // 'birth',
        'status',
        'name',
        'created_at',
        'updated_at',
        'avatar',
        'is_active',
       // 'sex',
    ];

    public $changeable = [
        'nickname',
        'open_id',
        'sns_open_id',
        'union_id',
        'mobile',
        'name',
        'status',
        'birth',
        'updated_at',
        'avatar',
        'is_active',
        'sex'
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'nickname' => 'string',
        'open_id' => 'string',
        'sns_open_id' => 'string',
        'union_id' => 'string',
        'mobile' => 'string',
        'avatar' => 'string',
    ];

    /**
     * Validation rules
     *
     * @var array
     */
    public static $rules = [
        'open_id' => 'required|string',
        'union_id' => 'required|string',
        'mobile' => 'requried|string',
    ];

    /**
     * @param $searchOptions
     * @return mixed
     */
    public function getQueryBySearchOptions($searchOptions)
    {
        $qb = self::newQuery();

        if (empty($searchOptions)) {
            return $qb;
        }

        !empty($searchOptions['keywords']) && $qb = $qb
            ->where('nickname', 'like', '%' . $searchOptions['keywords']. '%')
            ->orWhere('mobile', 'like', '%' . $searchOptions['keywords']. '%');
        unset($searchOptions['keywords']);

        foreach ($searchOptions as $key => $value) {
            if (is_array($value)) {
                $qb->whereIn($key, $value);
            } elseif (is_string($value) || is_numeric($value)) {
                $qb->where($key, $value);
            }
        }

        return $qb;
    }
}
